package cn.edu.cuit.elena.web.service;

import java.io.IOException;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.cuit.elena.common.SackConstants;
import cn.edu.cuit.elena.db.dao.BaseDao;
import cn.edu.cuit.elena.trace.Tracer;
import cn.edu.cuit.elena.transaction.controller.RunTimeExceptionSignal;
import cn.edu.cuit.elena.web.System;
import cn.edu.cuit.elena.web.service.AppSQL.UMSQL;
import cn.edu.cuit.elena.web.tool.JsonHelper;

public class UserManagementSvt
    extends HttpServlet
{

    static final String LOAD_USER = "user";
    static final String LOAD_USERGROUP = "usergroup";
    static final String ADD_USER = "adduser";
    static final String DELETE_USER = "deleteuser";
    static final String UPDATA_USER = "updateuser";
    static final String ADD_USERGROUP = "addusergroup";

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public static final String URL = "/usermanagement.svt";

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
    {

        doPost( request, response );
    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
    {

        response.setContentType( "text/html" );

        String para = request.getParameter( "kind" );
        Writer writer = response.getWriter();
        BaseDao baseDao = System.getBaseDao();

        if( LOAD_USER.equals( para ) )
        {
            List<Map<String, String>> users = baseDao.queryForMap( UMSQL.ALL_USERS.sql() );

            String json = JsonHelper.getNewInstance().toJson( users );

            Tracer.debugTrace( UserManagementSvt.class, "UserManagement.svt : " + json, null );

            writer.write( json );
        }
        else if( LOAD_USERGROUP.equals( para ) )
        {
            ResultSet resultSet = baseDao.query( "select * from usergroup" );
            Map<String, List<Map<String, List<Map<String, String>>>>> tree = new HashMap<String, List<Map<String, List<Map<String, String>>>>>();
            List<Map<String, List<Map<String, String>>>> nodes = new LinkedList<Map<String, List<Map<String, String>>>>();
            try
            {
                while( resultSet.next() )
                {
                    String usergroup = resultSet.getString( "usergroup" );
                    List<Map<String, String>> nodeContent = baseDao.queryForMap( UMSQL.USER_GROUP_BY_ID.sql(),
                        usergroup );

                    for( Map<String, String> map : nodeContent )
                    {
                        map.put( "text", usergroup );
                    }

                    Map<String, List<Map<String, String>>> node = new HashMap<String, List<Map<String, String>>>();
                    node.put( usergroup, nodeContent );
                    nodes.add( node );
                }
            }
            catch( SQLException e )
            {
                Tracer.fatalTrace( UserManagementSvt.class, "UserManagementSvt exception : " + e.getMessage(), e );
                throw new RunTimeExceptionSignal( e );
            }

            tree.put( "root", nodes );

            String json = JsonHelper.getNewInstance().toJson( tree );

            Tracer.debugTrace( UserManagementSvt.class, "UserManagementSvt json : " + json, null );

            writer.write( json );

        }
        else if( ADD_USER.equals( para ) )
        {
            String username = request.getParameter( "username" ) == null
                || request.getParameter( "username" ).equals( "null" ) ? "" : request.getParameter( "username" );
            String password = request.getParameter( "password" ) == null
                || request.getParameter( "password" ).equals( "null" ) ? "" : request.getParameter( "password" );
            String gender = request.getParameter( "gender" ) == null
                || request.getParameter( "gender" ).equals( "null" ) ? "" : request.getParameter( "gender" );
            String comments = request.getParameter( "comments" ) == null
                || request.getParameter( "comments" ).equals( "null" ) ? "" : request.getParameter( "comments" );
            String usergroup = request.getParameter( "usergroup" ) == null
                || request.getParameter( "usergroup" ).equals( "null" ) ? "" : request.getParameter( "usergroup" );

            baseDao.insertOneRow( SackConstants.SQL.ADD_USER.sql(),
                Arrays.asList( username, password, usergroup, gender, comments ) );

            writer.write( SackConstants.SUCCESS );
        }
        else if( UPDATA_USER.equals( para ) )
        {
            String username = request.getParameter( "username" ) == null
                || request.getParameter( "username" ).equals( "null" ) ? "" : request.getParameter( "username" );
            String password = request.getParameter( "password" ) == null
                || request.getParameter( "password" ).equals( "null" ) ? "" : request.getParameter( "password" );
            String gender = request.getParameter( "gender" ) == null
                || request.getParameter( "gender" ).equals( "null" ) ? "" : request.getParameter( "gender" );
            String comments = request.getParameter( "comments" ) == null
                || request.getParameter( "comments" ).equals( "null" ) ? "" : request.getParameter( "comments" );
            String usergroup = request.getParameter( "usergroup" ) == null
                || request.getParameter( "usergroup" ).equals( "null" ) ? "" : request.getParameter( "usergroup" );

            baseDao.insert( SackConstants.SQL.UPDATE_USER.sql(),
                Arrays.asList( password, usergroup, gender, comments, username ) );

            writer.write( SackConstants.SUCCESS );

        }
        else if( DELETE_USER.equals( para ) )
        {
            String username = request.getParameter( "username" ) == null
                || request.getParameter( "username" ).equals( "null" ) ? "" : request.getParameter( "username" );

            baseDao.execute( SackConstants.SQL.DELETE_USER.sql() + "'" + username + "'" );

            writer.write( SackConstants.SUCCESS );
        }
        else if( ADD_USERGROUP.equals( para ) )
        {

        }
        else if( "group".equals( para ) )
        {
            List<List<String>> rows = baseDao.queryForList( "select * from elena.usergroup", new LinkedList<String>() );
            
        }
        writer.flush();
        writer.close();
    }

    void loadGroupTree( Writer writer ) throws IOException
    {
        BaseDao baseDao = System.getBaseDao();
        List<Map<String, String>> result = baseDao.queryForMap( UMSQL.ALL_USER_GROUPS.sql() );
        writer.write( JsonHelper.getNewInstance().toJson( result ) );
    }

    void loadUserTree( Writer writer ) throws IOException
    {
        BaseDao baseDao = System.getBaseDao();
        List<Map<String, String>> result = baseDao.queryForMap( UMSQL.ALL_USERS.sql() );
        writer.write( JsonHelper.getNewInstance().toJson( result ) );
    }
}
